import cgi
import datetime
import urllib
import webapp2
import jinja2
import os
import structs
import re
import helpers

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

from google.appengine.ext import db
from google.appengine.api import users

#The webpage a user sees when coming to the site, either homepage or welcome page
class MainPage(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        courses = [1, 2]
        #set the proper template and log in/out url, and if logged load the courses 
        #the user is in
        userEntity = None
        if helpers.userCheck(user, True):
            #get the user object in the database
            userEntity = structs.People.getPerson(user)
            templateName = "home.html"
            #display which courses the user can go into, its printed out in the template
            courses = structs.Course.get(userEntity.courses)
            #log in url
            logUrl = users.create_logout_url(self.request.uri)
            template_values = {      
                'courses': courses,
                'logUrl': logUrl,
                'user': user,
                'userEntity': userEntity,
            }           
        else:
            templateName = "welcome.html"
            logUrl = users.create_login_url(self.request.uri)        
            template_values = {'logUrl': logUrl,}

        template = jinja_environment.get_template(templateName)
        self.response.out.write(template.render(template_values))

#the webpage for a course, display all of the directories in the course
#keep all the logURLs there, as before
class CoursePage(webapp2.RequestHandler):    
    def get(self):  
        rePattern = re.compile("/[^/]+$") #the course ID is at the end of the URL     
        user = users.get_current_user() #again, check if this is a valid sign-in
        #get the URL, provided by jinja in order to access the right course
        thisURL = self.request.uri        
        #sample URL: www.studyvolved.appspot.com/course/7210493/question/982349
        result = rePattern.findall(thisURL)
        #if this is a valid ID, should be split into two parts
        thisCourse = 0
        if len(result) > 0: #this is a non-empty array
            key = result[0]
            thisCourse = structs.Course.get(key[1:key.__len__()])                   
        else:
            courseKey = 99999999999999 #RE failed                   
        #get the courseKey from the Course object in structs
        
        #set the proper template and log in/out url, 
        #if logged in, load the categories within this course        
        if helpers.userCheck(user, True):         
            #get the user object in the database
            userEntity = structs.People.getPerson(user)
            #ensure that user is in course
            if not thisCourse.key() in userEntity.courses:
                self.redirect("/")
                return
            templateName = "course.html" #new defined webpage for this course menu
            #get access to the this course's categories
            categories = thisCourse.Categories   
            defaultQuestions = [] 
            defaultCategoryID = 0
            for category in categories: 
                if category.name == "Default": #only add questions found in default category
                    for item in category.questions:
                        defaultQuestions.append(db.get(item))                   
                    defaultCategoryID = category.key()
                    break
            clarifications = []
            for clarification in thisCourse.Clarifications:
                clarifications.append(clarification)
            #log out url
            logUrl = users.create_logout_url(self.request.uri)
            template_values = {
                'user': user,
                'userEntity': userEntity,
                'course': thisCourse,
                'categories': categories,
                'clarifications': clarifications,
                'logUrl': logUrl,
                'defaultQuestions': defaultQuestions,
                'defaultCategoryID': defaultCategoryID
            }
            template = jinja_environment.get_template(templateName)
            self.response.out.write(template.render(template_values))                           
        else: #redirects to the log-in page, since this user knows what to access
            self.redirect(users.create_login_url(self.request.uri))               
        
        
class CategoryPage(webapp2.RequestHandler):
    
    def get(self):        
        rePattern = re.compile("/[^/]+$") #the category ID is at the end of the URL   
        user = users.get_current_user() #again, check if this is a valid sign-in
        #in template: pass along category object itself, the questions, the course and user
        #get the URL, provided by jinja in order to access the right course
        thisURL = self.request.uri       
        result = rePattern.findall(thisURL)
        #if this is a valid ID, should be split into two parts
        if len(result) > 0: #this is a non-empty array            
            key = result[0]
            thisCategory = structs.Category.get(key[1:key.__len__()])           
            thisCourse = thisCategory.course #.course is already a Course object, I think
        else:           
            categoryKey = 99999999999999 #RE failed                   
        #get the categoryKey from the Course object in structs
         
        #set the proper template and log in/out url, 
        #if logged in, load the categories within this course        
        if helpers.userCheck(user, True):
            #get the user object in the database
            userEntity = structs.People.getPerson(user)
            templateName = "category.html" #new defined webpage for this course menu
            #ensure that user is in course
            if not thisCourse.key() in userEntity.courses:
                self.redirect("/")
                return
            #get access to the this course's categories
            questions = []
            for item in thisCategory.questions:
                questions.append(db.get(item))                                     
            #log out url
            logUrl = users.create_logout_url(self.request.uri)  
            template_values = {
                'user': user,
                'userEntity': userEntity,
                'course': thisCourse,
                'category': thisCategory,
                'questions': questions,
                'logUrl': logUrl,
            }    
            template = jinja_environment.get_template(templateName)
            self.response.out.write(template.render(template_values))                       
        else: #redirects to the log-in page, since this user knows what to access
            self.redirect(users.create_login_url(self.request.uri))       

class QuestionPage(webapp2.RequestHandler):   
    #to jinja: course, category, question and user
    #www.studyvolved.appspot.com/category/32949843/question/20934804
    #www.studyvolved.appspot.com/ category /category_ID/question/question_ID

    def get(self):        
        user = users.get_current_user() #again, check if this is a valid sign-in
        
        #set the proper template and log in/out url, 
        #if logged in, load the categories within this course        
        if helpers.userCheck(user, True):
            thisURL = self.request.uri       
            #if this is a valid ID, should be split into two parts
        
            categorySplit = re.findall("category/[^/]+", thisURL)
            thisCategory = structs.Category.get(categorySplit[0][9:categorySplit[0].__len__()])
            questionSplit = re.findall("question/[^/]+", thisURL)
            thisQuestion = structs.Question.get(questionSplit[0][9:questionSplit[0].__len__()])
            #get the categoryKey from the Course object in structs
            thisCourse = thisCategory.course
            #thisCourse = 0
            #get the user object in the database
            userEntity = structs.People.getPerson(user)
            #ensure that user is in course
            if not thisCourse.key() in userEntity.courses:
                self.redirect("/")
                return
            #gets all the answers to this specific question. Category IDs are unique
            answers = db.GqlQuery("SELECT * "
                                  "FROM Answer "
                                  "WHERE category = :1 AND question = :2",
                                  thisCategory, thisQuestion)
                       
            templateName = "question.html" #new defined webpage for this course menu                                  
            #log out url
            logUrl = users.create_logout_url(self.request.uri)
            template_values = {
                'user': user,
                'userEntity': userEntity,
                'course': thisCourse,
                'category': thisCategory,
                'question': thisQuestion,
                'logUrl': logUrl,  
                'studentResponses': answers        
            }    
            template = jinja_environment.get_template(templateName)
            self.response.out.write(template.render(template_values))           
        else: #redirect to a log-in page
            self.redirect(users.create_login_url(self.request.uri))       

app = webapp2.WSGIApplication([(r"/", MainPage),
                               (r"/course/[^/]+", CoursePage),
                               (r"/category/[^/]+", CategoryPage),
                               (r"/category/[^/]+/question/[^/]+", QuestionPage),
                               (r"/getCourse", helpers.GetCourse),
                               (r"/listCourses", helpers.CourseLister),
                               (r"/listCategories", helpers.CategoryLister),
                               (r"/listQuestions", helpers.QuestionLister),
                               (r"/listClarifications", helpers.ClarificationLister),
                               (r"/getCategory", helpers.GetCategory),
                               (r"/makeCourse", helpers.CourseMaker),
                               (r"/makeCategory", helpers.CategoryMaker),
                               (r"/makeQuestion", helpers.QuestionMaker),
                               (r"/makeClarification", helpers.ClarificationMaker),
                               (r"/ansQuestion", helpers.QuestionAnswer),
                               (r"/findQuestion", helpers.FindQuestion),
                               (r"/getAnswers", helpers.GetAnswers),
                               (r"/getDisplays", helpers.GetDisplays),
                               (r"/setDisplays", helpers.SetDisplays),
                               (r"/getDistribution", helpers.CourseDistribution),
                               (r"/createCKey", helpers.CKeyMaker)], debug = True)            